package domain;
import java.sql.ParameterMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Date;
import java.util.Vector;
import db.DBManager;

public class PostsManager {

	LRUCache<String, PostDO> lruCache;
	DBManager _dbManager = DBManager.getDBManager();
	PreparedStatement prepStmt;

	PostsManager(){}

	public void  addPost(PostDO p){

		String query = "INSERT INTO Posts VALUES(" + null + ",?,'" +  p.getPubDate() + "',?,?,?)";
		
		try {
			prepStmt = _dbManager.getConnection().prepareStatement(query);
			prepStmt.setString(1, p.getUser());
			prepStmt.setString(2, p.getTitle());
			prepStmt.setString(3, p.getContent());
			prepStmt.setString(4, p.getLTags());
			
			System.out.println("executing: " + prepStmt);
			
			prepStmt.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
//	public static void main(String[] args){
//		PostsManager _pManager = new PostsManager();
//		_pManager.addPost(new PostDO(null, "misha", new Timestamp(new Date().getTime()), "tititss", "connt", "tag15"));
//	}

	public Vector<PostDO> getPostsOf(String username, int limit){
		Vector<PostDO> posts = new Vector<PostDO>();

		try {
			String query = "SELECT * FROM Posts " +
			"WHERE username = '" + username + "' " +
			"ORDER BY pubdate desc " +
			"limit " + limit;
			
			DBManager dm = DBManager.getDBManager();
			ResultSet res = dm.query(query);
			posts = resultSetToPosts(res);
		} catch (SQLException e) {

			e.printStackTrace();
		}

		return posts;
	}

	public Vector<PostDO> getNextPosts(Date startDate, int num){
		Vector<PostDO> posts = new Vector<PostDO>();
		String query;
		try {
			if(startDate != null){
				query = "SELECT * FROM Posts " +
				"WHERE pubdate < '"+ new Timestamp(startDate.getTime()) +"'"+
				"ORDER BY pubdate desc " + 
				"LIMIT " + num;
			}else{
				query = "SELECT * FROM Posts " +
				"ORDER BY pubdate desc " + 
				"LIMIT " + num;
			}

			DBManager dm = DBManager.getDBManager();
			ResultSet res = dm.query(query);
			posts = resultSetToPosts(res);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return posts;
	}

	public Vector<PostDO> getPrevPosts(Date startDate, int num){
		Vector<PostDO> posts = new Vector<PostDO>();
		try {
			String query = "SELECT * FROM Posts " +
			"WHERE pubdate > '"+ new Timestamp(startDate.getTime()) +"'"+
			"ORDER BY pubdate desc " + 
			"LIMIT " + num;

			DBManager dm = DBManager.getDBManager();
			ResultSet res = dm.query(query);
			posts = resultSetToPosts(res);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return posts;
	}
	
	public Vector<PostDO> getNextPostsWithTags(Date startDate, String tags, int num) {
		String[] tagsArr = tags.split(" ");
		Vector<PostDO> posts = new Vector<PostDO>();

		try {
			DBManager dm = DBManager.getDBManager();

			for (String tag : tagsArr) {
				String query = "SELECT * FROM Posts WHERE tags like '%" + tag + "%' ORDER BY pubdate" +
								"and  pubdate < '"+ new Timestamp(startDate.getTime()) +"'"+"" +
								"ORDER BY pubdate desc " + 
								"LIMIT " + num;
				
				ResultSet res = dm.query(query);
				posts.addAll(resultSetToPosts(res));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}

		return posts;
	}
	
	public Vector<PostDO> getPrevPostsWithTags(Date startDate, String tags, int num) {
		String[] tagsArr = tags.split(" ");
		Vector<PostDO> posts = new Vector<PostDO>();

		try {
			DBManager dm = DBManager.getDBManager();

			for (String tag : tagsArr) {
				String query = "SELECT * FROM Posts WHERE tags like '%" + tag + "%' ORDER BY pubdate" +
								"and  pubdate > '"+ new Timestamp(startDate.getTime()) +"'"+"" +
								"ORDER BY pubdate desc " + 
								"LIMIT " + num;
				
				ResultSet res = dm.query(query);
				posts.addAll(resultSetToPosts(res));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}

		return posts;
	}

//	public int getNumOfNext(Date startDate){
//		int rowCount = 0;
//		try{
//
//			String query = "SELECT COUNT(*) FROM Posts " +
//			"WHERE pubdate < '"+ new Timestamp(startDate.getTime()) +"'";
//
//			DBManager dm = DBManager.getDBManager();
//			ResultSet res = dm.query(query);
//
//			rowCount = res.getInt(1);
//
//		} catch (SQLException e) {
//			e.printStackTrace();
//		}
//		return rowCount;
//	}

//	public int getNumOfPrev(Date startDate){
//		int rowCount = 0;
//		try{
//
//			String query = "SELECT COUNT(*) FROM Posts " +
//			"WHERE pubdate > '"+ new Timestamp(startDate.getTime()) +"'";
//
//			DBManager dm = DBManager.getDBManager();
//			ResultSet res = dm.query(query);
//
//			rowCount = res.getInt(1);
//
//
//		} catch (SQLException e) {
//			e.printStackTrace();
//		}
//		return rowCount;
//	}

//	public Vector<PostDO> getLastPosts(int num){
//		Vector<PostDO> posts = new Vector<PostDO>();
//
//		try {
//			String query = "SELECT * FROM Posts " +
//			//"WHERE pubdate >= '"+ new Timestamp(new Date().getTime()) +"' " +
//			"ORDER BY pubdate desc " + 
//			"LIMIT " + num;
//			DBManager dm = DBManager.getDBManager();
//			ResultSet res = dm.query(query);
//			posts = resultSetToPosts(res);
//		} catch (SQLException e) {
//
//			e.printStackTrace();
//		}
//		return posts;
//	}

	public String getPostsTags(){
		String tags;

		DBManager dm = DBManager.getDBManager();
		String query = "SELECT tags FROM Posts";
		ResultSet res = dm.query(query);
		tags = resultSetToTags(res);

		return tags;
	}

	private String resultSetToTags(ResultSet res){
		String tags = "";
		String postTags = null;

		try{
			while (res.next()) {	
				postTags = res.getString("TAGS");

				if(postTags != null && postTags != ""){
					String[] tagsInPost = postTags.split(" ");

					for(String tagInPost : tagsInPost){
						if(!tags.contains(tagInPost))
							tags += tagInPost + " ";
					}
				}
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return tags.substring(0, tags.length() - 1);
	}

	/**
	 * @param res
	 * @throws SQLException
	 */
	private Vector<PostDO> resultSetToPosts(ResultSet res)
	throws SQLException {
		Vector<PostDO> posts = new Vector<PostDO>();
		Integer id = null;
		String user = null, title = null, content = null, postTags = null;
		Date pubDate;
		
		while (res.next()) {
			id = res.getInt("ID");
			user = res.getString("USERNAME");
			pubDate = new Date(res.getTimestamp("PUBDATE").getTime());
			title = res.getString("TITLE");
			content = res.getString("CONTENT");
			postTags = res.getString("TAGS");
			PostDO p = new PostDO(id+"", user, pubDate, title, content, postTags);
			if (!posts.contains(p))
				posts.add(p);
		}
		return posts;
	}


	//	public Post getPost(String postID, String postUser){
	//
	//		// try take it from cache
	//		Post p = lruCache.get(postID+"#"+postUser);
	//		if(p != null)
	//			return p;
	//		
	//		//
	//		try {
	//			String query = "SELECT * FROM Posts" +
	//						   "WHERE ID = '"+postID+"' AND USERNAME = '"+ postUser+"'";
	//			
	//			
	//			DBManager dm = DBManager.getDBManager();
	//			
	//			ResultSet res = dm.query(query);
	//			
	//			Integer id = null; String user = null, title = null, content = null , tags = null;
	//			long pubdate = 0;
	//			if(res.next()){
	//				id = res.getInt("ID");
	//				user = res.getString("USERNAME");
	//				pubdate = res.getDate("PUBDATE").getTime();
	//				title = res.getString("TITLE");
	//				content = res.getString("CONTENT");
	//				tags = res.getString("ID");
	//			}
	//			
	//			p = new Post(id,user,pubdate,title,content,tags);
	//
	//			
	//		} catch (SQLException e) {
	//			
	//			e.printStackTrace();
	//		}
	//
	//		return p;		
	//	}


//	public void printAllPostsInDB(){
//
//		try {
//			String query = "SELECT * FROM Posts";
//
//			ResultSet res = _dbManager.query(query);
//
//			int id;
//			long pubdate;
//			String user = null, title = null, content = null , tags = null;
//
//			while(res.next()){
//				id = res.getInt("ID");
//				user = res.getString("USERNAME");
//				pubdate = res.getDate("PUBDATE").getTime();
//				title = res.getString("TITLE");
//				content = res.getString("CONTENT");
//				tags = res.getString("TAGS");
//				System.out.println("ID: " + id +", USER: " + user + ", PUBDATE:" + new Date(pubdate) + ", TITLE:" + title +", CONTENT: " + content + ", TAGS:" + tags);
//			}
//		} catch (SQLException e) {
//			e.printStackTrace();
//		}
//
//	}

//	public void printAllPostsOfUser(String user){
//
//		Vector<PostDO> posts = getPostsOf(user);
//
//		for(PostDO p : posts){
//			System.out.println(p.getId() +", " + p.getUser() + ", " + p.getPubDate() + ", " + p.getTitle() +", " + p.getContent() + ", " + p.getLTags());
//		}
//	}

	//	public void printAllPostsFromTo(Date from, Date to){
	//
	//		Vector<PostDO> posts = getPostsFromTo(from, to);
	//
	//		for(PostDO p : posts){
	//			System.out.println(p.getId() +", " + p.getUser() + ", " + p.getPubDate() + ", " + p.getTitle() +", " + p.getContent() + ", " + p.getLTags());
	//		}
	//	}

//	public void printAllPostsWithTags(String tags){
//
//		Vector<PostDO> posts = getPostsWithTags(tags);
//
//		for(PostDO p : posts){
//			System.out.println(p.getId() +", " + p.getUser() + ", " + p.getPubDate() + ", " + p.getTitle() +", " + p.getContent() + ", " + p.getLTags());
//		}
//	}

}
